package org.persistente.manipula.conexao;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;

public class FonteConexaoPool extends FonteConexaoAbstrata {

    private Connection conexao;
    private BasicDataSource dataSource;

    public FonteConexaoPool(DriverBanco driver, String usuario, String senha) {
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driver.getNomeDriver());
        dataSource.setUrl(driver.getStringConexao());
        dataSource.setUsername(usuario);
        dataSource.setPassword(senha);
        setDriverBanco(driver);
    }

    public void fechaConexao() {
        try {
            dataSource.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Connection getConexao() {
        if (conexao != null) {
            conexao = novaConexao();
        }
        return conexao;
    }

    @Override
    public Connection novaConexao() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new ConexaoException("Não foi possível obter conexão com o banco de dados", e);
        }
    }
}
